//
//  ScreeningView.swift
//  AirTravel
//
//  Created by apple on 2021/7/15.
//

import UIKit
protocol ScreeningDelegate:NSObjectProtocol {
    func screeningClick(data:Dictionary<String,Any>)
}

class ScreeningView: UIView {
    
    var contentView:UIView!
    weak var delegate: ScreeningDelegate?
    @IBOutlet weak var collView: UICollectionView!
    @IBOutlet weak var leftTab: UITableView!
    
    /// 完成
    @IBOutlet weak var completeBtn: UIButton!
    /// 清空
    @IBOutlet weak var emptyBtn: UIButton!
    let identifyIR = "IntelligentRankingCell"
    let identifyPR = "PriceReusableView"
    let identifyPS = "PriceStarColl"
    var dataSouce : Array<Any>?
    var brandArray = [String]()
    var facilityArray = [String]()
    var isPreferential = false
    
    
    
    // 初始化时将xib中的view添加进来
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView = loadViewFromNib()
        contentView.frame = self.bounds
        contentView.backgroundColor = UIColor.white
        self.insertSubview(contentView, at: 0)
        
        self.emptyBtn.layer.cornerRadius = 6
        self.emptyBtn.layer.borderWidth = 1
        self.emptyBtn.layer.borderColor = UIColor.init(r: 212, g: 212, b: 212).cgColor
        self.emptyBtn.addTarget(self, action: #selector(empty), for: .touchUpInside)
        
        self.completeBtn.layer.cornerRadius = 6
        self.completeBtn.layer.masksToBounds = true
        self.completeBtn.addTarget(self, action: #selector(complete), for: .touchUpInside)
        
        self.leftTab.dataSource = self
        self.leftTab.delegate = self
        self.leftTab.tag = 0
        self.leftTab.rowHeight = 50
        self.leftTab.register(UINib.init(nibName: "IntelligentRankingCell", bundle: nil), forCellReuseIdentifier: identifyIR)
        self.leftTab.tableFooterView = UIView.init()
        
        self.collView.dataSource = self
        self.collView.delegate = self
        let layout1 = UICollectionViewFlowLayout.init()
        layout1.scrollDirection = .vertical
        
        layout1.itemSize = .init(width: (SCREEN_WIDTH - 30 - 12 - 90) / 3, height: 40)
        layout1.minimumInteritemSpacing = 6
        layout1.sectionInset = UIEdgeInsets.init(top: 6, left: 15, bottom: 6, right: 15)
        self.collView.collectionViewLayout = layout1
        self.collView.register(UINib.init(nibName: "PriceReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: identifyPR)
        self.collView.register(UINib.init(nibName: "PriceStarColl", bundle: nil), forCellWithReuseIdentifier: identifyPS)
        
        
    }
    
    // 初始化时将xib中的view添加进来
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // 加载xib
    func loadViewFromNib() -> UIView {
        let className = type(of: self)
        let bundle = Bundle(for: className)
        let name = NSStringFromClass(className).components(separatedBy: ".").last
        let nib = UINib(nibName: name!, bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        view.backgroundColor = UIColor.clear
        return view
    }
    
    @objc func empty() {
        GKCover.hideWithoutAnimation()
    }
    
    @objc func complete() {
        var mutBrand = [String]()
        for item in self.brandArray {
            if item.isEmpty == false {
                mutBrand.append(item)
            }
        }
        let brand = mutBrand.joined(separator: ",")
        
        var mutFacil = [String]()
        for item in self.facilityArray {
            if item.isEmpty == false {
                mutFacil.append(item)
            }
        }
        let facility = mutFacil.joined(separator: ",")
        
        self.delegate?.screeningClick(data: ["brand":brand,"facility":facility])
        GKCover.hideWithoutAnimation()
    }
    
    func setUpData(array:Array<Any>) {
        self.dataSouce = array
        if let array = self.dataSouce {
            self.brandArray.removeAll()
            self.facilityArray.removeAll()
            for item in array {
                let dic = item as? Dictionary<String,Any>
                let keyword = "\(dic?["keyword"] ?? "")"
                let infolist = dic?["infolist"] as? Array<Any>
                guard let infoArray = infolist else { return }
                if keyword == "品牌" {
                    for _ in infoArray {
                        self.brandArray.append("")
                    }
                }else if keyword == "设施服务"{
                    for _ in infoArray {
                        self.facilityArray.append("")
                    }
                }
            }
        }
        self.leftTab.reloadData()
        self.collView.reloadData()
    }
}

extension ScreeningView:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSouce?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifyIR) as! IntelligentRankingCell
        cell.selectionStyle = .none
        if let array = self.dataSouce {
            let dic = array[indexPath.row] as? Dictionary<String,Any>
            cell.contentLab.text = "\(dic?["keyword"] ?? "")"
        }
        return cell
    }
}

extension ScreeningView:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return self.dataSouce?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let array = self.dataSouce else { return 0 }
        let dic = array[section] as? Dictionary<String,Any>
        let infolist = dic?["infolist"] as? Array<Any>
        if infolist?.isEmpty == true {
            return 0
        }else{
            return infolist?.count ?? 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifyPS, for: indexPath) as! PriceStarColl
        guard let array = self.dataSouce else { return cell }
        let dic = array[indexPath.section] as? Dictionary<String,Any>
        let infolist = dic?["infolist"] as? Array<Any>
        let keyword = "\(dic?["keyword"] ?? "")"
        if infolist?.isEmpty == false {
            let dict = infolist?[indexPath.row] as? Dictionary<String,Any>
            if keyword == "优惠促销" {
                cell.contentLab.text = "\(dict?["name"] ?? "")"
                if self.isPreferential {
                    cell.contentLab.textColor = Orange_COLOR
                }else{
                    cell.contentLab.textColor = .black
                }
            }else if keyword == "品牌" {
                cell.contentLab.text = "\(dict?["HotelBrandName"] ?? "")"
                let str = self.brandArray[indexPath.row]
                if str.isEmpty {
                    cell.contentLab.textColor = .black
                }else{
                    cell.contentLab.textColor = Orange_COLOR
                }
            }else if keyword == "设施服务" {
                cell.contentLab.text = "\(dict?["ParentName"] ?? "")"
                let str = self.facilityArray[indexPath.row]
                if str.isEmpty {
                    cell.contentLab.textColor = .black
                }else{
                    cell.contentLab.textColor = Orange_COLOR
                }
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        //1.取出section的headerView
        let headerView : PriceReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifyPR, for: indexPath) as! PriceReusableView
        guard let array = self.dataSouce else { return headerView }
        let dic = array[indexPath.section] as? Dictionary<String,Any>
        let keyword = "\(dic?["keyword"] ?? "")"
        headerView.titleLab.text = keyword
        headerView.priceLab.isHidden = true
        return headerView
    }
    
    //header高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: SCREEN_WIDTH, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        guard let array = self.dataSouce else { return }
        let dic = array[indexPath.section] as? Dictionary<String,Any>
        let keyword = "\(dic?["keyword"] ?? "")"
        let infolist = dic?["infolist"] as? Array<Any>
        guard let infoArray = infolist else { return }
        switch keyword {
        case "品牌":
            let str = self.brandArray[indexPath.row]
            let dict = infoArray[indexPath.row] as? Dictionary<String,Any>
            let HotelBrandId = "\(dict?["HotelBrandId"] ?? "")"
            if str.isEmpty {
                self.brandArray[indexPath.row] = HotelBrandId
            }else{
                self.brandArray[indexPath.row] = ""
            }
        case "设施服务":
            let str = self.facilityArray[indexPath.row]
            let dict = infoArray[indexPath.row] as? Dictionary<String,Any>
            let ParentId = "\(dict?["ParentId"] ?? "")"
            if str.isEmpty {
                self.facilityArray[indexPath.row] = ParentId
            }else{
                self.facilityArray[indexPath.row] = ""
            }
        default:
            self.isPreferential = !self.isPreferential
        }
        self.collView.reloadData()
    }
}
